﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using CloudShot.Core.Interfaces;
using CloudShot.Entities;
using CloudShot.Interfaces;
using CloudShot.Logic;
using CloudShot.Properties;
using CloudShot.Services;
using CloudShot.Utils;

namespace CloudShot.Forms
{
  internal partial class RecordPreviewForm : Form
  {
    private readonly INotificationService _notificationService;
    private readonly IConfigurationSection _appConfigurationSection;
    private readonly IFormHotkeyService _hotkeyService;

    private readonly Color _initialBackColor;
    private readonly Color _hoverBackColor = Color.FromArgb(215, 215, 215);
    private bool _isMouseOverPlayStopControl;
    private float _gifProgress;

    public RecordPreviewForm(Image animatedImage, StorageContainer storageContainer, INotificationService notificationService,
                             IConfigurationSection appConfigurationSection)
    {
      _notificationService = notificationService;
      _appConfigurationSection = appConfigurationSection;

      Icon = Resources.applicationIcon;
      InitializeComponent();

      uploadButton.SetStorageContainer(storageContainer);

      playerControl.Image = animatedImage;
      playerControl.Size = animatedImage.Size;
      playStopControl.Image = Resources.start_record;
      progressPanel.Width = playerControl.Width;

      _initialBackColor = playStopControl.BackColor;

      progressControl.Width = playerControl.Right - progressControl.Left;
      progressControl.Text = "";

      playerControl.Play();

      UpdatePlayBtnVisual();

      playerControl.ProgressChanged += OnProgressChanged;
      progressControl.Invalidate();

      _hotkeyService = new FormHotkeyService(this);

      _hotkeyService.RegisterHotkey(AppHotKeys.SaveImage, OnSaveClick);
      _hotkeyService.RegisterHotkey(AppHotKeys.UploadImage, OnUploadClick);
      _hotkeyService.RegisterHotkey(AppHotKeys.PreviewPlayPause, OnPlayPauseClick);
      _hotkeyService.RegisterHotkey(AppHotKeys.Cancel, OnCancelClick);

      playerControl.Click += OnPlayPauseClick;

      SetTooltipText(saveButton, Resources.Shared_Save, AppHotKeys.SaveImage);
      SetTooltipText(uploadButton, Resources.Shared_Upload, AppHotKeys.UploadImage);
      SetTooltipText(cancelButton, Resources.Shared_Cancel, AppHotKeys.Cancel);
    }

    //TODO copy paste from captuer form. Move this method to helper?
    private void SetTooltipText(Control item, string text, Hotkey hotkey)
    {
      toolTip1.SetToolTip(item, string.Format("{0} ({1})", text, hotkey));
    }

    private void OnProgressChanged(float prorgess)
    {
      _gifProgress = prorgess;
      progressControl.Invalidate();
    }

    private void OnProgressControlPaint(object sender, PaintEventArgs e)
    {
      const int progressLineWidth = 3;
      int yLinePos = (progressControl.Height - progressLineWidth) / 2;

      using (var allProgressBrush = new SolidBrush(Color.FromArgb(196, 196, 196)))
      using (var filledProgressBrush = new SolidBrush(Color.Black))
      {
        var rectangleAll = new Rectangle(0, yLinePos, progressControl.Width, progressLineWidth);
        e.Graphics.FillRectangle(allProgressBrush, rectangleAll);

        int filledSize = (int)(progressControl.Width * _gifProgress);
        var filledRectangle = new Rectangle(0, yLinePos, filledSize, progressLineWidth);

        e.Graphics.FillRectangle(filledProgressBrush, filledRectangle);
      }
    }

    private void UpdatePlayBtnVisual()
    {
      if (playerControl.IsPlaying)
      {
        SetTooltipText(playStopControl, Resources.RecordPreviewForm_PauseTooltip, AppHotKeys.PreviewPlayPause);
        playStopControl.Image = Resources.record_preview_pause;
      }
      else
      {
        SetTooltipText(playStopControl, Resources.RecordPreviewForm_PlayTooltip, AppHotKeys.PreviewPlayPause);
        playStopControl.Image = Resources.record_preview_play;
      }

      playStopControl.BackColor = _isMouseOverPlayStopControl ? _hoverBackColor : _initialBackColor;
    }

    #region Event Handler

    private void OnPlayPauseClick(object sender, EventArgs e)
    {
      if (playerControl.IsPlaying)
        playerControl.Pause();
      else
        playerControl.Play();

      UpdatePlayBtnVisual();
    }

    private void OnRestartClick(object sender, EventArgs e)
    {
      DialogResult = DialogResult.Retry;
      Close();
    }

    private void OnSaveClick(object sender, EventArgs e)
    {
      var saveShotDialog = new SaveShotDialog(_appConfigurationSection, ShotType.Record)
      {
        ImageFormats = new[]
        {
          ImageFormat.Gif
        }
      };

      if (saveShotDialog.ShowDialog() != DialogResult.OK)
        return;

      string fileName = saveShotDialog.FileName;

      if (playerControl.Image != null)
        playerControl.Image.SafeSave(fileName, saveShotDialog.SelectedImageFormat);

      _notificationService.ShowInfo(Resources.Notifications_RecordTitle, string.Format(Resources.Notifications_RecordBody, fileName), () => AppHelper.OpenInViewer(fileName));

      Close();
    }

    private void OnUploadClick(object sender, EventArgs e)
    {
      DialogResult = DialogResult.OK;
      Close();
    }

    private void playStopControl_MouseLeave(object sender, EventArgs e)
    {
      _isMouseOverPlayStopControl = false;
      UpdatePlayBtnVisual();
    }

    private void playStopControl_MouseEnter(object sender, EventArgs e)
    {
      _isMouseOverPlayStopControl = true;
      UpdatePlayBtnVisual();
    }

    private void OnCancelClick(object sender, EventArgs e)
    {
      DialogResult = DialogResult.Cancel;
      Close();
    }

    #endregion
  }
}